package com.kkwrite.regimen.consumer.controller.carousel;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.kkwrite.regimen.common.entity.dto.OutDTO;
import com.kkwrite.regimen.consumer.controller.constant.Constant;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/** 
 * 首页轮播图模块
 *
 * @author Soosky Wang
 * @date 2018年7月23日 上午9:24:09 
 * @version 1.0.0
 */
@Api(value = "轮播图模块")
@RestController
@RequestMapping("/carousel")
public class CarouselController {

	private static final Logger logger = LoggerFactory.getLogger(CarouselController.class);
	
	private static final Long HOME_CAROUSE_MODULE_ID = 1L;
	
	@Resource(name = "restTemplate")
	private RestTemplate restTemplate;
	
	@ApiOperation(value = "查询首页轮播图")
	@GetMapping("/gethomecarousel")
	public OutDTO getHomeCarousel() {
		if (logger.isDebugEnabled()) {
			logger.debug("查询首页轮播图");
		}
		
		OutDTO outDTO = null;
		try {
			String url = Constant.SERVICE_PREFIX + "/module/getmodule/" + HOME_CAROUSE_MODULE_ID;
			outDTO = restTemplate.getForObject(url, OutDTO.class);
			
			if (outDTO == null) {
				return new OutDTO("failed", "没有查询到数据");
			}
			
			Map module = (LinkedHashMap) outDTO.getData();
			if (module != null) {
				List<LinkedHashMap> modulteItems = (ArrayList<LinkedHashMap>) module.get("moduleItems");
				if (modulteItems != null && modulteItems.size() > 0) {
					for (Map modulteItem: modulteItems) {
						List<LinkedHashMap> pictures = (List<LinkedHashMap>) modulteItem.get("pictures");
						if (pictures != null) {
							if (pictures.size() >= 1) {
								LinkedHashMap picture = pictures.get(0);
								modulteItem.put("moduleItemImage", picture.get("pictureUrl"));
								modulteItem.remove("pictures");
							}
						}
					}
				}
			}
			
			return outDTO;
		} catch (RestClientException e) {
			logger.error("查询首页轮播图出错，_" + e.getMessage());
			e.printStackTrace();
			return new OutDTO("failed", e.getMessage());
		}
	}
	
}
